const superagent = require('superagent')
const Response = require('./response')

/**
 *
 */
class Downloader {
  constructor() {
    this.requestCount = 0  // 请求总个数
    this.requestFaild = 0  // 失败的请求数
    this.responseCount = 0 // 响应数
  }

  down(request) {
    let method = request.method.toUpperCase()
    switch (method) {
      case 'GET':
        return this.downGet(request)
      case 'POST':
        return this.downPost(request)
      default:
        throw new Error('请求方法有误，暂时只有 GET 方法')
    }
  }

  downGet(request) {
    return new Promise(((resolve, reject) => {
      this.requestCount++
      superagent.get(request.url)
        .then(res => {
          let {status, headers, text} = res
          let response = new Response({request, status, headers, text})
          this.responseCount++
          resolve(response)
        })
        .catch(err => {
          this.requestFaild++
          console.log(`下载${request.url}时异常：`, err)
        })
    }))
  }

  downPost(request) {
    throw new Error('POST请求方法还没写')
  }
}


module.exports = Downloader
